package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import jodd.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.hmdp.content.ERRORContent.BLOG_NO;
import static com.hmdp.content.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private IFollowService followService;

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog -> {
            this.queryBlogUser(blog);
            this.isBlogLike(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryMyBlog(Integer current) {

        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        // 根据用户查询
        Page<Blog> page = query()
                .eq("user_id", user.getId()).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    @Override

    public Result saveBlog(Blog blog) {
        // 获取登录用户
        Long userId = UserHolder.getUser().getId();
        blog.setUserId(userId);
        // 保存探店博文
        save(blog);
        //获取粉丝信息
        List<Follow> followUser = followService.query().eq("follow_user_id", userId).list();
        //发送给粉丝
        for (Follow follow : followUser){
            Long followId = follow.getUserId();
            String key =FEED_KEY+followId;
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogById(Long id) {
        //查询blog
        Blog blog = getById(id);
        if (blog == null){
            return Result.fail(BLOG_NO);
        }
        //查询blog相关的用户
        queryBlogUser(blog);
        //查询blog是否被点赞
        isBlogLike(blog);
        return Result.ok(blog);
    }

    /**
     * 修改点赞数量
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //1获取登入用户
        Long userId = UserHolder.getUser().getId();
        //2判断当前用户是否已经点赞
        String key = BLOG_LIKED_KEY+id;
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        //2.1如果没有点赞，可以点赞
        if(score == null){
            //数据库点赞加一
            boolean isUpdate = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isUpdate){
                //保存用户到redis1的set集合 zadd

                stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());
            }
        }else {
            //2.2如果点赞，取消点赞
            // 修改点赞数量
            boolean isUpdate = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isUpdate){
                //点赞减少一，删除redis里该用户
                stringRedisTemplate.opsForZSet().remove(key,userId.toString());
            }

        }
        return Result.ok();
    }

    /**
     * 点赞排名查询
     * @param id
     * @return
     */
    @Override
    public Result queryBlogLikes(Long id) {
        String key = BLOG_LIKED_KEY+id;
        //查询前五个点赞的用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key,0,4);
        if (top5 == null){
            return Result.ok(Collections.emptyList());
        }
        //解析用户数据
        List<Long> userIds = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String uids = StrUtil.join(",", userIds);
        //根据用户id查询用户
        List<UserDTO> userDTOs = userService.query()
                .in("id",userIds).last("ORDER BY FIELD( id,"+ uids+")").list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        //
        return Result.ok(userDTOs);
    }

    /**
     * 查询笔记（共同关注
     * @param current
     * @param id
     * @return
     */
    @Override
    public Result queryBlogByUserId(Integer current, Long id) {
        // 根据用户查询
        Page<Blog> page = query()
                .eq("user_id", id).page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        return Result.ok(records);
    }

    /**
     * 滚动查询
     * @param max
     * @param offset
     * @return
     */
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //1.获取当前用户
        Long userId = UserHolder.getUser().getId();
        //2查询收件箱子
        String key = FEED_KEY +userId;
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().
                reverseRangeByScoreWithScores(key, 0, max, offset,2);
        //解析数据
        if (typedTuples == null || typedTuples.isEmpty())
        {
            return Result.ok();
        }
        long minTime = 0;
        int os = 1;
        List<Long> ids = new ArrayList<>(typedTuples.size());
        for (ZSetOperations.TypedTuple<String> tup : typedTuples){
            ids.add(Long.valueOf(tup.getValue()));
            Long  score = tup.getScore().longValue();
            if (score == minTime){
                os++;
            }else {
                minTime = score;
                os=1;
            }
        }
        os = minTime == max ? os + offset : os;
        String uids = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).
                last("ORDER BY FIELD( id," + uids + ")").list();
        for (Blog blog :blogs){
            //查询blog相关的用户
            queryBlogUser(blog);
            //查询blog是否被点赞
            isBlogLike(blog);
        }
        ScrollResult rs = new ScrollResult();
        rs.setList(blogs);
        rs.setMinTime(minTime);
        rs.setOffset(os);
        return Result.ok(rs);
    }


    /**
     * 修改用户部分信息
     * @param blog
     */
    private void queryBlogUser(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
    private void isBlogLike(Blog blog){
        //1获取登入用户
        UserDTO user = UserHolder.getUser();
        if (user == null){
            //用户未登入，无需查询是否点赞
            return;
        }
        Long userId = user.getId();
        //2判断当前用户是否已经点赞
        String key = BLOG_LIKED_KEY+ blog.getId();

        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());

    blog.setIsLike(score != null);
    }

}
